package br.com.massai.controller.filter;

import java.io.IOException;

import javax.inject.Inject;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.com.massai.view.utils.NavigationUtil;

@WebFilter("/LoginFilter")
public class LoginFilter implements Filter {

	@Inject private SessionControl access;

    public LoginFilter() { }

	public void destroy() { }

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		if(((HttpServletRequest) request).getSession() != null){
			if(access.loggedIn())
				chain.doFilter(request, response);
			else 
				((HttpServletResponse) response).sendRedirect("/massai/" + NavigationUtil.TO_LOGIN + ".xhtml");
		} else {
			((HttpServletResponse) response).sendRedirect("/massai/pages/access/" + NavigationUtil.TO_HOME + ".xhtml");
		}
	}

	public void init(FilterConfig fConfig) throws ServletException { }
}
